#include "HelloWorldScene.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"



USING_NS_CC;

using namespace cocostudio::timeline;

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();
    
    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();
    
    // add layer as a child to scene
    scene->addChild(layer);
    
    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();
    auto closeItem = MenuItemImage::create(
                                           "CloseNormal.png",
                                           "CloseSelected.png",
                                           CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
    
    closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
                                origin.y + closeItem->getContentSize().height/2));
//    auto rootNode = CSLoader::createNode("MainScene.csb");
//    addChild(rootNode, 1);
    // create menu, it's an autorelease object
    auto menu = Menu::create(closeItem, NULL);
     menu->setPosition(Vec2::ZERO);
     this->addChild(menu, 1);
    CCLOG("sss");
    auto ui=cocostudio::GUIReader::getInstance()->widgetFromJsonFile("Kasama_1/Kasama_1.ExportJson");
    addChild(ui);
    Button *startgame=(Button*)Helper::seekWidgetByName(ui,"Button_Start");
    startgame->addTouchEventListener(this,toucheventselector(HelloWorld::startGame));
    Button *optionDialog=(Button*)Helper::seekWidgetByName(ui,"Button_Option");
    optionDialog->addTouchEventListener(this,toucheventselector(HelloWorld::optionDialog));
    Button * historyButton=(Button*)Helper::seekWidgetByName(ui,"Button_History");
    historyButton->addTouchEventListener(this,toucheventselector(HelloWorld::historyDialog));
    Button *aboutButton=(Button*)Helper::seekWidgetByName(ui,"Button_about");
    aboutButton->addTouchEventListener(this,toucheventselector(HelloWorld::openAboutDialog));
    auto listener = EventListenerKeyboard::create();
    listener->onKeyReleased = CC_CALLBACK_2(HelloWorld::keyBackClicked,this);
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,this);
    
    Button * closeButton1=(Button*)Helper::seekWidgetByName(global->historyDialog,"Button_close");
    Button * closeButton2=(Button*)Helper::seekWidgetByName(global->optionDialog,"Button_Close");
    CheckBox * checkBox=(CheckBox*)Helper::seekWidgetByName(global->optionDialog,"CheckBox_music");
    Slider * slidevolume=(Slider*)Helper::seekWidgetByName(global->optionDialog,"Slider");
    slidevolume->setPercent(global->volume);
    slidevolume->addEventListenerSlider(this,sliderpercentchangedselector(HelloWorld::sliderchangecallBack));
    checkBox->setSelectedState(global->isPlayMusic);
    closeButton1->addTouchEventListener(this,toucheventselector(HelloWorld::closeDialog));
    closeButton2->addTouchEventListener(this,toucheventselector(HelloWorld::closeDialog));
    checkBox->addEventListenerCheckBox (this,checkboxselectedeventselector(HelloWorld::changeMusicState));
    global->historyDialog->setVisible(false);
    global->optionDialog->setVisible(false);
    addChild(global->historyDialog,2);
    addChild(global->optionDialog,2);
    
    aboutDialog=cocostudio::GUIReader::getInstance()->widgetFromJsonFile("about/about.ExportJson");
    addChild(aboutDialog,2);
    aboutDialog->setVisible(false);
    Button * closeButton3=(Button*)Helper::seekWidgetByName(aboutDialog,"Button_close");
    closeButton3->addTouchEventListener(this,toucheventselector(HelloWorld::closeDialog));
    //加载成绩
    int element[3];
    
    element[0]=UserDefault::getInstance()->getIntegerForKey("firstscore",0);
    element[1]=UserDefault::getInstance()->getIntegerForKey("secondscore",0);
    element[2]=UserDefault::getInstance()->getIntegerForKey("thirdscore",0);
    int info=UserDefault::getInstance()->getIntegerForKey("name",0);
    CCLOG("info:%d",info);
    char scorestr[10];
    sprintf(scorestr,"%d",element[0]);
    global->score1->setString(scorestr);
    sprintf(scorestr,"%d",element[1]);
    global->score2->setString(scorestr);
    sprintf(scorestr,"%d",element[2]);
    global->score3->setString(scorestr);
    
    //创建分享按钮, 参数1为按钮正常情况下的图片, 参数2为按钮选中时的图片,参数3为友盟appkey, 参数4为分享回调
    //	UMShareButton *shareButton = UMShareButton::create("share2.png","share2selected.png", "54e882a9fd98c52b7e0002cd",
    //		share_selector(shareCallback)) ;
    //	// 显示在友盟分享面板上的平台
    //	vector<int>* platforms = new vector<int>();
    //	platforms->push_back(SINA);
    //	platforms->push_back(RENREN) ;
    //	platforms->push_back(DOUBAN) ;
    //	platforms->push_back(QZONE) ;
    //	platforms->push_back(QQ) ;
    //	// 设置友盟分享面板上显示的平台
    //	shareButton->setPlatforms(platforms);
    //	// 设置文本分享内容
    //	shareButton->setShareContent("umeng social cocos2d-x sdk.") ;
    //	// 设置要分享的图片, 图片支持本地图片和url图片, 但是url图片必须以http://或者https://开头
    //	shareButton->setShareImage("images") ;
    //	// 设置按钮的位置
    //	shareButton->setPosition(ccp(0, 0));
    //	shareButton->setAnchorPoint(Vec2(1,0));
    //	shareButton->setScale(0.5);
    //	// 然后开发者需要将该按钮添加到游戏场景中
    //	CCMenu* pMenu = CCMenu::create(shareButton, NULL);
    //	pMenu->setPosition(VisibleRect::right());
    //	this->addChild(pMenu, 1);
    
    // ********************** 设置平台信息 ***************************
    // CCUMSocialSDK *sdk = shareButton->getSocialSDK();
    // sdk->setQQAppIdAndAppKey("设置QQ的app id", "appkey");
    // sdk->setWeiXinAppInfo("设置微信和朋友圈的app id","app key");
    // sdk->setYiXinAppKey("设置易信和易信朋友圈的app id");
    // sdk->setLaiwangAppInfo("设置来往和来往动态的app id",
    //                  "设置来往和来往动态的app key", "我的应用名");
    // sdk->setFacebookAppId("你的facebook appid");
    // 设置用户点击一条图文分享时用户跳转到的目标页面, 一般为app主页或者下载页面
    // sdk->setTargetUrl("http://www.umeng.com/social");
    //     // 打开或者关闭log
    // sdk->setLogEnable(true) ;
    // **********************   END ***************************
    
    
    return true;
}


void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
    MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
    return;
#endif
    
    Director::getInstance()->end();
    
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}
void HelloWorld::startGame(Ref * pSender,TouchEventType type)
{
    auto scene =GameScene::createScene();
    switch ((int)type)
    {
        case (int)(cocos2d::ui::Widget::TouchEventType::BEGAN):
            
            break;
        case (int)(cocos2d::ui::Widget::TouchEventType::ENDED):
            
            Director::getInstance()->replaceScene(TransitionFade::create(1.5,scene));
        case (int)(cocos2d::ui::Widget::TouchEventType::CANCELED):
            
            break;
        default:
            break;
    }
}
void HelloWorld::keyBackClicked(EventKeyboard::KeyCode keyCode, Event* event)
{
    if(keyCode==EventKeyboard::KeyCode::KEY_BACK){
        Director::getInstance()->end();
    }
}
void HelloWorld::optionDialog(Ref *pSender,TouchEventType type)
{
    global->optionDialog->setAnchorPoint(Vec2(0.5,0.5));
    global->optionDialog->setPosition(VisibleRect::center());
    switch ((int)type)
    {
        case (int)(cocos2d::ui::Widget::TouchEventType::BEGAN):
            
            break;
        case (int)(cocos2d::ui::Widget::TouchEventType::ENDED):
            
            //addChild(global->optionDialog);
            global->optionDialog->setVisible(true);
        case (int)(cocos2d::ui::Widget::TouchEventType::CANCELED):
            
            break;
        default:
            break;
    }
}
void HelloWorld::closeDialog(Ref *pSender,TouchEventType type)
{
    global->optionDialog->setVisible(false);
    global->historyDialog->setVisible(false);
    aboutDialog->setVisible(false);
}
void HelloWorld::historyDialog(Ref *pSender,TouchEventType type)
{
    
    switch ((int)type)
    {
        case (int)(cocos2d::ui::Widget::TouchEventType::BEGAN):
            
            break;
        case (int)(cocos2d::ui::Widget::TouchEventType::ENDED):
            
            //addChild(global->optionDialog);
            global->historyDialog->setVisible(true);
            
        case (int)(cocos2d::ui::Widget::TouchEventType::CANCELED):
            
            break;
        default:
            break;
    }
}
void HelloWorld::changeMusicState(Ref* sender,CheckBoxEventType type)
{
    switch (type)
    {
        case CHECKBOX_STATE_EVENT_SELECTED:
            global->isPlayMusic=true;
            UserDefault::getInstance()->setBoolForKey("isPlay",global->isPlayMusic);
            if(!CocosDenshion::SimpleAudioEngine::getInstance()->isBackgroundMusicPlaying())
            {
                CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic(global->musicpath,true);
            }
            CCLOG("selected");//选中时响应
            break;
        case CHECKBOX_STATE_EVENT_UNSELECTED:
            global->isPlayMusic=false;
            CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic();
            CCLOG("unselected");//未选中时响应
            break;
        default:
            break;
    }
    UserDefault::getInstance()->setBoolForKey("isPlay",global->isPlayMusic);
}
void HelloWorld:: sliderchangecallBack(Ref * sender,SliderEventType type)
{
    Slider* slider;
    int percent;
    switch (type)
    {
        case SLIDER_PERCENTCHANGED:
            slider= dynamic_cast<Slider*>(sender);
            percent=slider->getPercent();
            UserDefault::getInstance()->setIntegerForKey("volume",percent);
            CCLOG("percent:%d",percent);
            global->volume=percent;
            CocosDenshion::SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(percent/100.0);
            break;
        default:
            break;
    }
    
}
void HelloWorld::openAboutDialog(Ref * sender,TouchEventType type)
{
    switch ((int)type)
    {
        case (int)(cocos2d::ui::Widget::TouchEventType::BEGAN):
            
            break;
        case (int)(cocos2d::ui::Widget::TouchEventType::ENDED):
            
            //addChild(global->optionDialog);
            aboutDialog->setVisible(true);
        case (int)(cocos2d::ui::Widget::TouchEventType::CANCELED):
            
            break;
        default:
            break;
    }
    
}
